<template>
  <div class="advanced-search-container">
    <el-card class="search-card" :body-style="{ padding: collapsed ? '5px' : '15px' }">
      <template #header>
        <div class="search-header">
          <div class="search-title">
            <el-icon><Search /></el-icon>
            <span>高级搜索</span>
          </div>
          <div class="search-actions">
            <el-button
              type="primary"
              size="small"
              @click="handleSearch"
              :loading="loading"
              :disabled="!hasValidConditions"
            >
              <el-icon><Search /></el-icon>
              <span>搜索</span>
            </el-button>
            <el-button
              type="info"
              size="small"
              plain
              @click="handleReset"
              :disabled="!hasAnyConditions"
            >
              <el-icon><RefreshLeft /></el-icon>
              <span>重置</span>
            </el-button>
            <el-button
              type="primary"
              size="small"
              text
              @click="toggleCollapse"
            >
              <el-icon v-if="collapsed"><ArrowDown /></el-icon>
              <el-icon v-else><ArrowUp /></el-icon>
            </el-button>
          </div>
        </div>
      </template>

      <div v-show="!collapsed" class="search-content">
        <!-- 常用搜索 -->
        <div class="quick-searches">
          <span class="label">常用搜索：</span>
          <div class="quick-search-items">
            <el-tag
              v-for="(saved, index) in savedSearches"
              :key="index"
              class="saved-search"
              :effect="saved.name === activeSearch ? 'dark' : 'plain'"
              @click="loadSavedSearch(saved)"
              closable
              @close.stop="removeSavedSearch(index)"
            >
              {{ saved.name }}
            </el-tag>
            <el-button type="primary" size="small" text @click="showSaveDialog">
              <el-icon><Plus /></el-icon>
              <span>保存当前搜索</span>
            </el-button>
          </div>
        </div>

        <!-- 关键字搜索 -->
        <div class="keyword-search">
          <el-autocomplete
            v-model="keywordQuery"
            :fetch-suggestions="fetchSuggestions"
            placeholder="关键词搜索（支持搜索查询内容和回答）"
            :trigger-on-focus="false"
            clearable
            @select="handleSelect"
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #suffix>
              <el-tooltip content="支持搜索内容、回答文本，多个关键词用空格分隔" placement="top">
                <el-icon><InfoFilled /></el-icon>
              </el-tooltip>
            </template>
            <template #default="{ item }">
              <div class="suggestion-item">
                <div>{{ item.value }}</div>
                <small>{{ item.description }}</small>
              </div>
            </template>
          </el-autocomplete>
        </div>

        <!-- 日期范围选择 -->
        <div class="date-range">
          <div class="date-quick-selectors">
            <div class="label">时间范围：</div>
            <div class="quick-buttons">
              <el-radio-group v-model="quickDateRange" size="small" @change="handleQuickDateChange">
                <el-radio-button label="today">今日</el-radio-button>
                <el-radio-button label="yesterday">昨日</el-radio-button>
                <el-radio-button label="thisWeek">本周</el-radio-button>
                <el-radio-button label="thisMonth">本月</el-radio-button>
                <el-radio-button label="custom">自定义</el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <div v-if="quickDateRange === 'custom'" class="custom-date-picker">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 1, 1, 23, 59, 59)
              ]"
              @change="handleCustomDateChange"
            />
          </div>
        </div>

        <!-- 高级条件筛选 -->
        <div class="advanced-filters">
          <div class="filter-row" v-for="(filter, index) in advancedFilters" :key="index">
            <el-select
              v-model="filter.field"
              placeholder="选择字段"
              class="filter-field"
              @change="() => handleFieldChange(index)"
            >
              <el-option
                v-for="field in availableFields"
                :key="field.value"
                :label="field.label"
                :value="field.value"
              />
            </el-select>

            <el-select
              v-model="filter.operator"
              placeholder="选择操作符"
              class="filter-operator"
              :disabled="!filter.field"
            >
              <el-option
                v-for="op in getOperatorsForField(filter.field)"
                :key="op.value"
                :label="op.label"
                :value="op.value"
              />
            </el-select>

            <!-- 根据字段类型显示不同的值输入控件 -->
            <component
              :is="getComponentForField(filter.field)"
              v-model="filter.value"
              :placeholder="'输入' + getFieldLabel(filter.field)"
              :field-config="getFieldConfig(filter.field)"
              class="filter-value"
              :disabled="!filter.operator"
            />

            <div class="filter-actions">
              <el-button
                type="danger"
                circle
                plain
                size="small"
                @click="removeFilter(index)"
                :disabled="advancedFilters.length === 1 && index === 0"
              >
                <el-icon><Delete /></el-icon>
              </el-button>

              <el-button
                v-if="index === advancedFilters.length - 1"
                type="primary"
                circle
                plain
                size="small"
                @click="addFilter"
              >
                <el-icon><Plus /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 保存搜索对话框 -->
    <el-dialog
      v-model="saveDialogVisible"
      title="保存搜索"
      width="400px"
    >
      <el-form :model="saveForm" ref="saveFormRef" :rules="saveFormRules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" placeholder="输入搜索名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="saveForm.description"
            type="textarea"
            :rows="3"
            placeholder="输入搜索描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="saveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSearch" :loading="savingSearch">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import {
  Search,
  Delete,
  Plus,
  ArrowUp,
  ArrowDown,
  RefreshLeft,
  InfoFilled
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 字段选择
const SearchValueText = defineComponent({
  name: 'SearchValueText',
  props: {
    modelValue: String,
    placeholder: String,
    fieldConfig: Object,
    disabled: Boolean
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const handleInput = (value) => {
      emit('update:modelValue', value)
    }

    return () => h(ElInput, {
      modelValue: props.modelValue,
      'onUpdate:modelValue': handleInput,
      placeholder: props.placeholder,
      disabled: props.disabled,
      clearable: true
    })
  }
})

const SearchValueSelect = defineComponent({
  name: 'SearchValueSelect',
  props: {
    modelValue: [String, Number, Array],
    placeholder: String,
    fieldConfig: Object,
    disabled: Boolean
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const handleChange = (value) => {
      emit('update:modelValue', value)
    }

    return () => h(ElSelect, {
      modelValue: props.modelValue,
      'onUpdate:modelValue': handleChange,
      placeholder: props.placeholder,
      disabled: props.disabled,
      multiple: props.fieldConfig?.multiple,
      clearable: true,
      style: { width: '100%' }
    }, () => (props.fieldConfig?.options || []).map(option =>
      h(ElOption, {
        key: option.value,
        label: option.label,
        value: option.value
      })
    ))
  }
})

const SearchValueNumber = defineComponent({
  name: 'SearchValueNumber',
  props: {
    modelValue: Number,
    placeholder: String,
    fieldConfig: Object,
    disabled: Boolean
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const handleChange = (value) => {
      emit('update:modelValue', value)
    }

    return () => h(ElInputNumber, {
      modelValue: props.modelValue,
      'onUpdate:modelValue': handleChange,
      placeholder: props.placeholder,
      disabled: props.disabled,
      min: props.fieldConfig?.min,
      max: props.fieldConfig?.max,
      step: props.fieldConfig?.step || 1,
      precision: props.fieldConfig?.precision,
      controls: true,
      style: { width: '100%' }
    })
  }
})

const SearchValueDate = defineComponent({
  name: 'SearchValueDate',
  props: {
    modelValue: String,
    placeholder: String,
    fieldConfig: Object,
    disabled: Boolean
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const handleChange = (value) => {
      emit('update:modelValue', value)
    }

    return () => h(ElDatePicker, {
      modelValue: props.modelValue,
      'onUpdate:modelValue': handleChange,
      type: props.fieldConfig?.type || 'date',
      placeholder: props.placeholder,
      disabled: props.disabled,
      valueFormat: props.fieldConfig?.format || 'YYYY-MM-DD',
      style: { width: '100%' }
    })
  }
})

// 组件配置
const componentMap = {
  'text': SearchValueText,
  'select': SearchValueSelect,
  'number': SearchValueNumber,
  'date': SearchValueDate
}

// 定义属性
const props = defineProps({
  // 是否显示正在加载
  loading: {
    type: Boolean,
    default: false
  },
  // 初始条件
  initialFilters: {
    type: Object,
    default: () => ({})
  },
  // 查询建议
  suggestions: {
    type: Array,
    default: () => []
  }
})

// 定义事件
const emit = defineEmits(['search', 'reset', 'update:filters'])

// 状态
const collapsed = ref(false)
const keywordQuery = ref('')
const quickDateRange = ref('')
const dateRange = ref([])
const advancedFilters = ref([
  { field: '', operator: '', value: '' }
])
const activeSearch = ref('')
const saveDialogVisible = ref(false)
const savingSearch = ref(false)
const saveForm = ref({
  name: '',
  description: ''
})
const saveFormRef = ref(null)
const saveFormRules = {
  name: [
    { required: true, message: '请输入搜索名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 从localStorage加载保存的搜索
const savedSearches = ref([])

// 字段定义
const availableFields = [
  { value: 'status', label: '查询状态', type: 'select', options: [
    { value: 'success', label: '成功' },
    { value: 'failed', label: '失败' },
    { value: 'timeout', label: '超时' },
    { value: 'processing', label: '处理中' },
    { value: 'waiting', label: '等待中' }
  ] },
  { value: 'user_id', label: '用户ID', type: 'text' },
  { value: 'dataset_id', label: '数据集ID', type: 'text' },
  { value: 'model_id', label: '模型ID', type: 'select', options: [
    { value: 'gpt-3.5', label: 'GPT-3.5' },
    { value: 'gpt-4', label: 'GPT-4' },
    { value: 'claude-2', label: 'Claude 2' },
    { value: 'claude-3', label: 'Claude 3' },
    { value: 'custom', label: '自定义模型' }
  ] },
  { value: 'query_tokens', label: '查询Token数', type: 'number' },
  { value: 'response_tokens', label: '回答Token数', type: 'number' },
  { value: 'execution_time', label: '执行时间(ms)', type: 'number' },
  { value: 'timestamp', label: '查询时间', type: 'date', format: 'YYYY-MM-DD HH:mm:ss' },
  { value: 'tags', label: '标签', type: 'select', multiple: true, options: [
    { value: 'important', label: '重要' },
    { value: 'bug', label: '问题' },
    { value: 'feedback', label: '反馈' },
    { value: 'feature', label: '功能请求' },
    { value: 'follow-up', label: '需跟进' }
  ] }
]

// 操作符定义
const operators = {
  text: [
    { value: 'contains', label: '包含' },
    { value: 'notContains', label: '不包含' },
    { value: 'equals', label: '等于' },
    { value: 'startsWith', label: '开头是' },
    { value: 'endsWith', label: '结尾是' }
  ],
  select: [
    { value: 'equals', label: '等于' },
    { value: 'notEquals', label: '不等于' },
    { value: 'in', label: '在列表中' },
    { value: 'notIn', label: '不在列表中' }
  ],
  number: [
    { value: 'equals', label: '等于' },
    { value: 'notEquals', label: '不等于' },
    { value: 'greaterThan', label: '大于' },
    { value: 'lessThan', label: '小于' },
    { value: 'between', label: '介于' }
  ],
  date: [
    { value: 'equals', label: '等于' },
    { value: 'before', label: '早于' },
    { value: 'after', label: '晚于' },
    { value: 'between', label: '介于' }
  ]
}

// 计算属性
const hasAnyConditions = computed(() => {
  return keywordQuery.value ||
         dateRange.value?.length ||
         quickDateRange.value ||
         advancedFilters.value.some(f => f.field && f.operator && f.value !== '')
})

const hasValidConditions = computed(() => {
  // 有关键词或日期范围，就认为是有效的
  if (keywordQuery.value ||
      dateRange.value?.length ||
      (quickDateRange.value && quickDateRange.value !== 'custom')) {
    return true
  }

  // 检查高级筛选是否有效
  return advancedFilters.value.some(f => f.field && f.operator && f.value !== '')
})

// 方法
const toggleCollapse = () => {
  collapsed.value = !collapsed.value
}

const getFieldConfig = (fieldValue) => {
  const field = availableFields.find(f => f.value === fieldValue)
  if (!field) return {}

  return {
    type: field.type,
    options: field.options,
    multiple: field.multiple,
    format: field.format
  }
}

const getComponentForField = (fieldValue) => {
  const field = availableFields.find(f => f.value === fieldValue)
  if (!field) return componentMap.text

  return componentMap[field.type] || componentMap.text
}

const getOperatorsForField = (fieldValue) => {
  const field = availableFields.find(f => f.value === fieldValue)
  if (!field) return operators.text

  return operators[field.type] || operators.text
}

const getFieldLabel = (fieldValue) => {
  const field = availableFields.find(f => f.value === fieldValue)
  return field ? field.label : fieldValue
}

const handleFieldChange = (index) => {
  const filter = advancedFilters.value[index]
  filter.operator = ''
  filter.value = ''
}

const addFilter = () => {
  advancedFilters.value.push({ field: '', operator: '', value: '' })
}

const removeFilter = (index) => {
  if (advancedFilters.value.length > 1) {
    advancedFilters.value.splice(index, 1)
  } else {
    // 如果只有一项，则清空它
    advancedFilters.value[0] = { field: '', operator: '', value: '' }
  }
}

const handleQuickDateChange = (value) => {
  if (value !== 'custom') {
    // 根据选择的快速日期范围设置日期
    let start = new Date()
    let end = new Date()
    let day = 0

    switch (value) {
      case 'today':
        start.setHours(0, 0, 0, 0)
        break
      case 'yesterday':
        start.setDate(start.getDate() - 1)
        start.setHours(0, 0, 0, 0)
        end.setDate(end.getDate() - 1)
        end.setHours(23, 59, 59, 999)
        break
      case 'thisWeek':
        day = start.getDay() || 7
        start.setDate(start.getDate() - day + 1)
        start.setHours(0, 0, 0, 0)
        break
      case 'thisMonth':
        start.setDate(1)
        start.setHours(0, 0, 0, 0)
        break
    }

    dateRange.value = [
      formatDate(start, 'YYYY-MM-DD HH:mm:ss'),
      formatDate(end, 'YYYY-MM-DD HH:mm:ss')
    ]
  }
}

const handleCustomDateChange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    quickDateRange.value = 'custom'
  }
}

const fetchSuggestions = (queryString, callback) => {
  const results = queryString
    ? props.suggestions.filter(item =>
        item.value.toLowerCase().includes(queryString.toLowerCase())
      )
    : props.suggestions

  // 可以在这里添加一些智能提示的逻辑
  // 比如根据用户最近的搜索记录，或者热门搜索词

  callback(results)
}

const handleSelect = (item) => {
  keywordQuery.value = item.value
}

const handleSearch = () => {
  // 构建搜索条件
  const filters = buildSearchFilters()

  // 触发搜索事件
  emit('search', filters)
  emit('update:filters', filters)
}

const handleReset = () => {
  keywordQuery.value = ''
  quickDateRange.value = ''
  dateRange.value = []
  advancedFilters.value = [{ field: '', operator: '', value: '' }]
  activeSearch.value = ''

  emit('reset')
  emit('update:filters', {})
}

const buildSearchFilters = () => {
  const filters = {}

  // 关键词
  if (keywordQuery.value) {
    filters.keyword = keywordQuery.value
  }

  // 时间范围
  if (dateRange.value && dateRange.value.length === 2) {
    filters.timeRange = dateRange.value
  }

  // 高级筛选
  advancedFilters.value.forEach(filter => {
    if (filter.field && filter.operator && filter.value !== '') {
      if (!filters.advanced) filters.advanced = []

      filters.advanced.push({
        field: filter.field,
        operator: filter.operator,
        value: filter.value
      })
    }
  })

  return filters
}

const loadSavedSearch = (savedSearch) => {
  // 重置当前条件
  keywordQuery.value = savedSearch.filters.keyword || ''

  // 设置日期范围
  if (savedSearch.filters.timeRange && savedSearch.filters.timeRange.length === 2) {
    dateRange.value = savedSearch.filters.timeRange
    quickDateRange.value = 'custom'

    // 检查是否匹配快速日期选择
    const start = new Date(savedSearch.filters.timeRange[0])
    const end = new Date(savedSearch.filters.timeRange[1])
    const now = new Date()

    // 今日
    const todayStart = new Date(now)
    todayStart.setHours(0, 0, 0, 0)
    const todayEnd = new Date(now)

    // 昨日
    const yesterdayStart = new Date(now)
    yesterdayStart.setDate(yesterdayStart.getDate() - 1)
    yesterdayStart.setHours(0, 0, 0, 0)
    const yesterdayEnd = new Date(now)
    yesterdayEnd.setDate(yesterdayEnd.getDate() - 1)
    yesterdayEnd.setHours(23, 59, 59, 999)

    // 检查匹配
    if (isSameDay(start, todayStart) && isSameDay(end, todayEnd)) {
      quickDateRange.value = 'today'
    } else if (isSameDay(start, yesterdayStart) && isSameDay(end, yesterdayEnd)) {
      quickDateRange.value = 'yesterday'
    }
    // 可以添加更多快速日期范围的匹配...
  } else {
    dateRange.value = []
    quickDateRange.value = ''
  }

  // 设置高级筛选
  if (savedSearch.filters.advanced && savedSearch.filters.advanced.length > 0) {
    advancedFilters.value = savedSearch.filters.advanced.map(adv => ({
      field: adv.field,
      operator: adv.operator,
      value: adv.value
    }))
  } else {
    advancedFilters.value = [{ field: '', operator: '', value: '' }]
  }

  activeSearch.value = savedSearch.name

  // 执行搜索
  handleSearch()
}

const showSaveDialog = () => {
  saveForm.value = {
    name: '',
    description: ''
  }
  saveDialogVisible.value = true
}

const saveSearch = async () => {
  // 表单验证
  try {
    await saveFormRef.value.validate()

    savingSearch.value = true

    const filters = buildSearchFilters()
    const newSavedSearch = {
      name: saveForm.value.name,
      description: saveForm.value.description,
      filters,
      createdAt: new Date().toISOString()
    }

    // 添加到保存的搜索中
    savedSearches.value.push(newSavedSearch)

    // 保存到localStorage
    localStorage.setItem('savedSearches', JSON.stringify(savedSearches.value))

    // 设置当前活动的搜索
    activeSearch.value = newSavedSearch.name

    saveDialogVisible.value = false
    ElMessage.success('搜索条件保存成功')
  } catch (error) {
    console.error('保存搜索失败', error)
  } finally {
    savingSearch.value = false
  }
}

const removeSavedSearch = (index) => {
  const removed = savedSearches.value.splice(index, 1)[0]

  // 更新localStorage
  localStorage.setItem('savedSearches', JSON.stringify(savedSearches.value))

  // 如果删除的是当前活动的搜索，重置活动搜索
  if (removed.name === activeSearch.value) {
    activeSearch.value = ''
  }

  ElMessage.success('已删除保存的搜索')
}

// 辅助函数
const formatDate = (date, format) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

const isSameDay = (date1, date2) => {
  return date1.getFullYear() === date2.getFullYear() &&
         date1.getMonth() === date2.getMonth() &&
         date1.getDate() === date2.getDate()
}

// 生命周期
onMounted(() => {
  // 从localStorage加载保存的搜索
  try {
    const saved = localStorage.getItem('savedSearches')
    if (saved) {
      savedSearches.value = JSON.parse(saved)
    }
  } catch (error) {
    console.error('加载保存的搜索失败', error)
  }

  // 初始化筛选条件
  if (props.initialFilters) {
    // 关键词
    keywordQuery.value = props.initialFilters.keyword || ''

    // 时间范围
    if (props.initialFilters.timeRange && props.initialFilters.timeRange.length === 2) {
      dateRange.value = props.initialFilters.timeRange
      quickDateRange.value = 'custom'
    }

    // 高级筛选
    if (props.initialFilters.advanced && props.initialFilters.advanced.length > 0) {
      advancedFilters.value = props.initialFilters.advanced.map(adv => ({
        field: adv.field,
        operator: adv.operator,
        value: adv.value
      }))
    }
  }
})

// 导入defineComponent和h
import { defineComponent, h } from 'vue'
import { ElInput, ElSelect, ElOption, ElInputNumber, ElDatePicker } from 'element-plus'

// 监听筛选条件变化，更新父组件
watch([keywordQuery, dateRange, advancedFilters], () => {
  if (hasValidConditions.value) {
    const filters = buildSearchFilters()
    emit('update:filters', filters)
  }
}, { deep: true })
</script>

<style scoped>
.advanced-search-container {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 4px;
  transition: all 0.3s;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.search-actions {
  display: flex;
  gap: 8px;
}

.search-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.quick-searches {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.label {
  font-weight: bold;
  color: var(--el-text-color-regular);
  white-space: nowrap;
}

.quick-search-items {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  flex: 1;
}

.saved-search {
  cursor: pointer;
  margin-right: 0;
}

.keyword-search {
  width: 100%;
}

.search-input {
  width: 100%;
}

.date-range {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.date-quick-selectors {
  display: flex;
  align-items: center;
  gap: 12px;
}

.advanced-filters {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.filter-row {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-field {
  flex: 2;
}

.filter-operator {
  flex: 2;
}

.filter-value {
  flex: 3;
}

.filter-actions {
  display: flex;
  gap: 4px;
}

.custom-date-picker {
  width: 100%;
}

.suggestion-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.suggestion-item small {
  color: var(--el-text-color-secondary);
  font-size: 0.8em;
}

@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
  }

  .filter-field, .filter-operator, .filter-value {
    width: 100%;
    flex: none;
  }
}
</style>
